package com.yupi.mianshiya.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.mianshiya.common.BaseResponse;
import com.yupi.mianshiya.common.DeleteRequest;
import com.yupi.mianshiya.common.ErrorCode;
import com.yupi.mianshiya.common.ResultUtils;
import com.yupi.mianshiya.constant.CommonConstant;
import com.yupi.mianshiya.exception.BusinessException;
import com.yupi.mianshiya.model.dto.comments.CommentsAddRequest;
import com.yupi.mianshiya.model.dto.comments.CommentsQueryRequest;
import com.yupi.mianshiya.model.entity.Comments;
import com.yupi.mianshiya.model.entity.User;
import com.yupi.mianshiya.model.vo.CommentsVO;
import com.yupi.mianshiya.service.CommentsService;
import com.yupi.mianshiya.service.UserService;
import com.yupi.mianshiya.utils.SqlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "评论接口")
@RestController
@RequestMapping("/comments")
@Slf4j
public class CommentsController {
    @Resource
    private UserService userService;

    @Resource
    private CommentsService commentsService;



    @ApiOperation("创建评论接口")
    @PostMapping("/add")
    public BaseResponse<Boolean> addComment(@RequestBody CommentsAddRequest commentsAddRequest, HttpServletRequest request) {
        //校验参数
        if (commentsAddRequest == null || commentsAddRequest.getContent() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long userid = loginUser.getId();
        String userName = loginUser.getUserName();
        String userAvatar = loginUser.getUserAvatar();
        Long replyUserId = commentsAddRequest.getReplyUserId();
         Comments comments = new Comments();
        if ( replyUserId!= null && replyUserId!= 0){
            User replyUser = userService.getById(replyUserId);
            if (replyUser == null){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"用户不存在");
            }
            if (replyUser.getIsDelete() == 1){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"已注销");
            }
               comments.setReplyUserName(replyUser.getUserName());
        }

            BeanUtils.copyProperties(commentsAddRequest, comments);
            comments.setUserId(userid);

            comments.setUserName(userName);
            comments.setUserAvatar(userAvatar);
            boolean save = commentsService.save(comments);
            if (!save) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"评论失败");
            }

        return ResultUtils.success(true);
        }


    @ApiOperation("获取评论接口")
    @GetMapping("/get")
    public BaseResponse<List<CommentsVO>> getComments(CommentsQueryRequest commentsQueryRequest, HttpServletRequest request) {
        //校验参数
        if (commentsQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        // 检查是否至少有一个参数不为null
        if (commentsQueryRequest.getId() == null &&
                commentsQueryRequest.getArticleId() == null &&
                commentsQueryRequest.getUserId() == null &&
                commentsQueryRequest.getParentId() == null &&
                commentsQueryRequest.getContent() == null) {
            //如果不是管理员，则至少需要提供一个查询参数
            if (!userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "至少需要提供一个查询参数");
            }
        }


        LambdaQueryWrapper<Comments> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断不为空才进去
        lambdaQueryWrapper.eq(commentsQueryRequest.getId() != null,Comments::getId, commentsQueryRequest.getId());
        lambdaQueryWrapper.eq(commentsQueryRequest.getArticleId() != null,Comments::getArticleId, commentsQueryRequest.getArticleId());
        lambdaQueryWrapper.eq(commentsQueryRequest.getUserId() != null,Comments::getUserId, commentsQueryRequest.getUserId());
        lambdaQueryWrapper.eq(commentsQueryRequest.getParentId() != null,Comments::getParentId, commentsQueryRequest.getParentId());
        lambdaQueryWrapper.like(commentsQueryRequest.getContent() != null,Comments::getContent, commentsQueryRequest.getContent());
        List<Comments> commentsList = commentsService.list(lambdaQueryWrapper);
        //把评论转换成VO
        List<CommentsVO> commentsVOList = commentsService.convertCommentsToVO(commentsList);
        return ResultUtils.success(commentsVOList);

    }

    @ApiOperation("删除评论接口")
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteComment(DeleteRequest deleteRequest, HttpServletRequest request) {
        //校验参数
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean admin = userService.isAdmin(request);
        if (!admin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        boolean remove = commentsService.removeById(deleteRequest.getId());
        if (!remove) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除失败");
        }
        return ResultUtils.success(true);



    }

    @ApiOperation("管理员分页获取评论接口")
    @GetMapping("/admin/get")
    public BaseResponse<Page<Comments>> getCommentsByAdmin(CommentsQueryRequest commentsQueryRequest, HttpServletRequest request) {
        //校验参数
        if (commentsQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        //分页查询
        Page<Comments> page = new Page<>(commentsQueryRequest.getCurrent(), commentsQueryRequest.getPageSize());
        QueryWrapper<Comments> queryWrapper = new QueryWrapper<>();
        //判断不为空才进去
        queryWrapper.eq(commentsQueryRequest.getId() != null, "id", commentsQueryRequest.getId());
        queryWrapper.eq(commentsQueryRequest.getArticleId() != null, "articleId", commentsQueryRequest.getArticleId());
        queryWrapper.eq(commentsQueryRequest.getUserId() != null, "userId", commentsQueryRequest.getUserId());
        queryWrapper.eq(commentsQueryRequest.getParentId() != null, "parentId", commentsQueryRequest.getParentId());
        queryWrapper.like(commentsQueryRequest.getContent() != null, "content", commentsQueryRequest.getContent());
        queryWrapper.orderByDesc(commentsQueryRequest.getSortField() != null, commentsQueryRequest.getSortField());

        // 排序规则
        String sortField = commentsQueryRequest.getSortField();
        String sortOrder = commentsQueryRequest.getSortOrder();
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);

        Page<Comments> commentsPage = commentsService.page(page, queryWrapper);
        return ResultUtils.success(commentsPage);

    }


}
